import websocket
import base64
import hmac
import hashlib
from datetime import datetime
from time import mktime
from urllib.parse import urlencode
from wsgiref.handlers import format_date_time
from urllib.parse import urlparse

def create_url(URL,AppKey,AppSecret):
    # 解析URL
    parsed_url = urlparse(URL)
    host = parsed_url.hostname
    path = parsed_url.path
    # 生成RFC1123格式的时间戳
    now = datetime.now()
    date = format_date_time(mktime(now.timetuple()))
    # 拼接字符串
    signature_origin = "host: {}\ndate: {}\n{} {} HTTP/1.1".format(host, date, "GET", path)
    # 进行hmac-sha256进行加密
    signature_sha = hmac.new(AppSecret.encode('utf-8'), signature_origin.encode('utf-8'),
                                digestmod=hashlib.sha256).digest()

    signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')
    authorization_origin = f'hmac api_key="{AppKey}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"'

    authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
    v = {
        'authorization':authorization,
        'host': host,
        'date': date
    }
    url = "{}{}{}".format(URL, '&' if parsed_url.query else '?', urlencode(v))
    return url

def on_message(ws, message):
    print(message)
    print("on message")
   

def on_error(ws, error):
    print(error)


def on_close(ws):
    print("### closed ###")

def on_open(ws):
    print("connect")
    req =  "{\"payload\":{\"functions\":{\"text\":[{\"name\":\"销售额查询\",\"description\":\"按条件查询历史销售额\",\"parameters\":{\"type\":\"object\",\"properties\":{\"name\":{\"description\":\"门店名称\",\"type\":\"string\"},\"day\":{\"description\":\"销售日期\",\"type\":\"string\"}}}}]},\"message\":{\"text\":[{\"role\":\"user\",\"content\":\"2025年9月1日蜘蛛王二店的销售额是多少\"}]}},\"parameter\":{\"chat\":{\"max_tokens\":1024,\"domain\":\"generalv3.5\",\"temperature\":0.5}},\"header\":{\"uid\":\"12345678\",\"app_id\":\"94b07ed1\"}}"
    ws.send(req)

def recog():
    url = create_url(URL='wss://spark-api.xf-yun.com/v3.5/chat', AppKey='35974ce45434ceee1a1906ef63c3521d',
                       AppSecret='NmE1ZjYzYmZjM2U5ZmI0M2JjYmE1ZTJk')
    ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close)
    ws.on_open = on_open
    ws.run_forever()

if __name__ == "__main__":
    recog()
